package com.me.controllers;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.me.bean.AjaxResp;
import com.me.entity.NewsRecords;
import com.me.service.SingleCharMsgService;
import com.me.service.UserInfoService;
import com.me.util.MapUtil;

@Controller
public class MsgController {

	@Autowired
	SingleCharMsgService singleCharMsgService;
	@Autowired
	UserInfoService userInfoService;
	@RequestMapping("/changeSingleMsgState")
	@ResponseBody
	@Transactional
	public AjaxResp changeSingleMsgState(String msg_id){
		AjaxResp ar=new AjaxResp();
		ar.setSuccess(false);
		List list=singleCharMsgService.getMsgById(Integer.parseInt(msg_id));
		if(list.size()==0 || list.isEmpty()){
			return ar;
		}
		NewsRecords nr=(NewsRecords)list.get(0);
		
		nr.setIsread(1);
		singleCharMsgService.UpdateMsgStateById(nr);
	
		ar.setSuccess(true);
		
		return ar;
	}
	
	@RequestMapping("/getNoReadMsg")
	@ResponseBody
	public AjaxResp getNoReadMsg(String account){
		AjaxResp ar=new AjaxResp();
		ar.setSuccess(false);
		int uid=userInfoService.getUserIdByAccount(account);
		List list=singleCharMsgService.getNoReadMsgByUserId(uid);
		String[] str_arr={"account","msg","time","type"};
		if(list.size()==0 || list.isEmpty()){
			ar.setData(list);
			return ar;
		}
		
		ar.setSuccess(true);
		ar.setData(MapUtil.arrayToList(list.size(), 4, list, str_arr));
		return ar;
	}
	
	
	@RequestMapping("/updateAllNoReadMsgState")
	@ResponseBody
	@Transactional
	public AjaxResp UpdateAllMsgStateByAccount(String account,String friaccount){
		AjaxResp ar=new AjaxResp();
		ar.setSuccess(false);
		
		int ruid=userInfoService.getUserIdByAccount(account);
		int suid=userInfoService.getUserIdByAccount(friaccount);
		List<NewsRecords> list=singleCharMsgService.getNoReadByTwoId(suid, ruid);
		if(list.size()==0 || list.isEmpty()){
			ar.setSuccess(true);
			return ar;
		}
		for(int i=0;i<list.size();i++){
			NewsRecords nr=list.get(i);
			nr.setIsread(1);
			singleCharMsgService.UpdateMsgStateById(nr);
			
		}
		ar.setSuccess(true);
		
		
		return ar;
	}
	
	
	
}
